using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using System.Security.Cryptography;


namespace RGBFinder
{
    public class WebConnection
    {

        public static readonly string VERSION = "1.0.0.0";

        public static void requestPosition(string nick, string level, string score, string time, Action<int> callback, Action error)
        {
            try
            {
                var hashalg = new SHA256Managed();

                byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
                var idh = hashalg.ComputeHash(id.Concat(Encoding.UTF8.GetBytes("tap")).ToArray());
                var phoneId = BitConverter.ToString(idh).Replace("-", "").ToLower();

                //time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                var param_string = "&phoneID=" + phoneId + "&nick=" + nick + "&score=" + score + "&level=" + level + "&time=" + time + "&vers=" + VERSION;
                
                var h = hashalg.ComputeHash(Encoding.UTF8.GetBytes("hash" + param_string + "tapS"));
                var hash = BitConverter.ToString(h).Replace("-", "").ToLower();

                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://chainingexpwp7.altervista.org/scoreTap.php?req=" + param_string + "&hash=" + hash);
                //HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://chainingexpwp7.altervista.org/score.php?req=" + param_string + "&hash=" + hash);

                req.Method = "GET";
                req.BeginGetResponse(
                    (asyncResult) =>
                    {
                        try
                        {
                            
                            HttpWebResponse objResponse = null;
                            StreamReader objs = null;

                            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                            objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
                            objs = new StreamReader(objResponse.GetResponseStream());
                            var html = objs.ReadToEnd();
                            var resp = html.Split('%');
                            h = hashalg.ComputeHash(Encoding.UTF8.GetBytes("hash" + resp[0] + "tap"));
                            hash = BitConverter.ToString(h).Replace("-", "").ToLower();
                            if (resp[1] != hash) 
                                return;
                            var infos = resp[0].Split('|');
                            try
                            {
                                callback(Int32.Parse(infos[0]));
                            }
                            catch (Exception) { }

                        }
                        catch (Exception e)
                        {
                            var prova = e;
                            e = e;
                        }
                    }, req);
            }
            catch (Exception e)
            {
                error();
            }
        }

        public static void updateOtherProduct(Action onSuccess)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://chainingexpwp7.altervista.org/appList_"+RGBFinder.Resources.Strings.LangId+".php");
               
                req.Method = "GET";
                req.BeginGetResponse(
                    (asyncResult) =>
                    {
                        try
                        {                            
                            HttpWebResponse objResponse = null;
                            StreamReader objs = null;

                            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                            objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
                            //objs = new StreamReader(objResponse.GetResponseStream());

                            var stream = objResponse.GetResponseStream();
                            byte [] buffer= new byte[stream.Length];
                            stream.Read(buffer,0,(int)stream.Length);
                            var enc = Encoding.GetEncoding("ISO-8859-1");
                            try
                            {
                                var ct = objResponse.Headers["Content-Type"];
                                var charset = ct.Split(',').First(st => st.Contains("charset")).Split('=')[1];
                                enc = Encoding.GetEncoding(charset);
                            }
                            catch (Exception) { }
                            var html = enc.GetString(buffer, 0, (int)stream.Length);
                            //var html = objs.ReadToEnd();
                            var apps_list = html.Split('\n').Select(app => app.Split('|').ToArray()).ToList();
                            //var apps_list_ids = apps_list.Select(app => app[0]);

                            //var to_remove = StateAndOptions.state.applications2.Keys.Except(apps_list_ids);
                            
                            ////foreach (var i in to_remove) 
                            ////    StateAndOptions.state.applications2.Remove(i);
                            var newAppList = new List<OurApplication>();

                            foreach (var a in apps_list)
                            {
                                //var a = apps_list.FirstOrDefault(app => app[0].Equals(id));
                                //if (StateAndOptions.state.applications2.Count(appl=>appl.id.Equals(id))==0 || StateAndOptions.state.applications2.First(appl=>appl.id.Equals(id)).revision < Int32.Parse(a[1]))
                                //{
                                    //var old = StateAndOptions.state.applications2.FirstOrDefault(appl => appl.id.Equals(id));
                                    //if (old != null) StateAndOptions.state.applications2.Remove(old);
                                    try
                                    {
                                        newAppList.Add(
                                            new OurApplication()
                                            {
                                                id=a[0],
                                                name = a[1],
                                                imageUri = a[2],                                             
                                                description=a[3]
                                            }
                                            );
                                    }
                                    catch (Exception)
                                    {
                                    }
                                    
                               }
                            StateAndOptions.state.applications2 = newAppList;
                                                        
                            try
                            {
                                onSuccess();
                            }
                            catch (Exception) { }

                        }
                        catch (Exception e)
                        {
                            var prova = e;
                            e = e;
                        }
                    }, req);
            }
            catch (Exception e)
            {
            }
        }

        public static void GetRequestStreamCallbackForBook(IAsyncResult asyncResult)
        {
            IAsyncResult ar = null;

            int i = 0;
        }


        protected static void GetScrapingResponse(IAsyncResult result)
        {
            int i = 1;
        }



    }

}
